import {
  PerspectiveCamera,
  Scene,
  WebGLRenderer,
  Object3D,
  Clock,
} from "three";
class Loop {
  #camera; // 相机
  #scene; // 场景
  #renderer; // 渲染
  #updatables = []; // 循环里的动画对象列表
  #clock; // 秒表
  /**
   * @param {PerspectiveCamera} camera - 相机
   * @param {Scene} scene - 场景
   * @param {WebGLRenderer} renderer - 渲染
   * @param {Object3D[]} updatables - 循环里的动画对象列表
   */
  constructor(camera, scene, renderer, updatables = []) {
    this.#camera = camera;
    this.#scene = scene;
    this.#renderer = renderer;
    this.#updatables = updatables;
    this.#clock = new Clock();
  }

  /**
   * @description - 动画循环开始
   */
  start() {
    this.#renderer.setAnimationLoop(() => {
      this.tick();
      this.#renderer.render(this.#scene, this.#camera);
    });
  }

  /**
   * @description - 动画循环结束
   */
  stop() {
    this.#renderer.setAnimationLoop(null);
  }

  /**
   * @description - 更新动画
   */
  tick() {
    // .getDelta告诉我们自上次调用.getDelta以来已经过去了多少时间。
    const delta = this.#clock.getDelta();
    for (const object of this.#updatables) {
      object.tick(delta);
    }
  }

  /**
   * @description - 添加动画对象
   * @param  {...Object3D} object
   */
  addObjectToUpdatables(...object) {
    this.#updatables.push(...object);
  }

  /**
   * @description - 删除动画对象
   * @param  {...Object3D} object
   */
  removeObjectFromUpdatables(...object) {
    this.#updatables = this.#updatables.filter((obj) => !object.includes(obj));
  }
}

export { Loop };
